package com.cheyun.netsalev3.repository

import androidx.paging.PageKeyedDataSource
import com.cheyun.netsalev3.bean.Yaoyue
import com.cheyun.netsalev3.bean.YaoyueParam
import com.cheyun.netsalev3.utils.api.*
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.util.*

class HomeTaskYaoyuePageRepository : BasePageRepository<YaoyueParam>() {
    var data=""
    init {
        //使用当前日期作为选取器中的默认日期
        val c = Calendar.getInstance()
        val year = c.get(Calendar.YEAR)
        val month = c.get(Calendar.MONTH)+1
        val day = c.get(Calendar.DAY_OF_MONTH)
        data="$year-$month-$day"
    }
    override fun loadInitial(params: PageKeyedDataSource.LoadInitialParams<Int>, callback: (data: MutableList<YaoyueParam>) -> Unit) {

        ApiClient.getInstance().getInviteData(1, data)
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(object : ApiCallback<BaseResp<Yaoyue>>() {
                    override fun onSuccess(t: BaseResp<Yaoyue>) {
                        t.data?.rows?.apply {
                            total.postValue(t.data!!.total)
                            callback(this)
                        }
                    }

                    override fun onError(ex: ApiException) {
                        networkState.postValue(NetworkState.error(ex.getMessage()))
                    }


                })
    }

    override fun loadAfter(params: PageKeyedDataSource.LoadParams<Int>, callback: PageKeyedDataSource.LoadCallback<Int, YaoyueParam>) {
        ApiClient.getInstance().getInviteData(params.key, data)
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(object : ApiCallback<BaseResp<Yaoyue>>() {
                    override fun onSuccess(t: BaseResp<Yaoyue>) {
                        t.data?.rows?.apply {
                            callback.onResult(this, params.key + 1)
                        }
                    }

                    override fun onError(ex: ApiException) {
                    }


                })
    }

    override fun loadBefore(params: PageKeyedDataSource.LoadParams<Int>, callback: PageKeyedDataSource.LoadCallback<Int, YaoyueParam>) {
        ApiClient.getInstance().getInviteData(params.key, data)
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(object : ApiCallback<BaseResp<Yaoyue>>() {
                    override fun onSuccess(t: BaseResp<Yaoyue>) {
                        t.data?.rows?.apply {
                            callback.onResult(this, params.key - 1)
                        }
                    }

                    override fun onError(ex: ApiException) {
                    }


                })
    }
}